#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2021/6/21
# @Author    :zhangxuchuo
# @Email     :zhangxuchuo@bbdservice.com
# @File      :TAX19_EntTaxrating_SX
# @Software  :PyCharm


'''eof
name:申请企业纳税评级
code:TAX19_EntTaxrating_SX
tableName:
columnName:
groups:场景业务校验-税务
dependencies:TX_SX_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import time,datetime
import pandas as pd
import math
from dateutil import rrule
from dateutil.relativedelta import relativedelta
import io

# reload(sys)
# sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
def inquireIsReportNo(data):
    """
    判断是否存在reportNo
    :param data:
    :return:True/False
    """
    try:

        is_reportNo = True if len(data.get("reportNo")) > 0 else False

    except:
        is_reportNo = False

    return is_reportNo

def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = TX_SX_DSJ["data"].get(table_Name)
        return data if isinstance(data, list) and len(data) > 0 else [{}]

    except:
        return [{}]

def dataPre(dataList=None, key=None):
    """
    对list里面的列表去重月份不标准的
    :param dataList:
    :param key:
    :return:
    """
    dataListTemp = dataList
    data = []
    for i in range(len(dataListTemp)):
        temp = dataListTemp[i].get(key)
        try:
            temp = int(temp)
        except:
            temp = None
            pass

        if temp:
            data.append(dataListTemp[i])
        else:
            pass

    if len(data) == 0:
        data = [{}]
    else:
        pass

    return data

def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """
    data_value = str(data_value)
    return_data = None
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data


def countdownTwoYearsTaxAmtCheck(CcrDate=None):
    """
    企业税务信用等级需在C级（含）以上，不包括M级的企业通过，否则拒绝。
    根据申请年份：
	税务纳税评级新增当年纳税评级的判断，优先判断，若当年纳税评级为D，则直接拒绝；
	根据申请月份：
    A、如果申请月份>5,取“当前年度-1”和“当前年度-2”,两年评级均大于等于C级才允许通过，否则拒绝。
    B、如果申请月份<=5,优先去取“当前年度-1”和“当前年度-2”，计算方法同上一条；
    如“当前年度-1”无数据，则取“当前年度-2”和“当前年度-3”，此时两年评级均大于等于C级才允许通过，否则拒绝。
    :param CcrDate: 测试时间，默认为None，
    :return:
    """
    try:
        factor = []
        if CcrDate is None:
            CcrMonth = datetime.datetime.now().month
            CcrYear = datetime.datetime.now().year
        else:
            # 用于分析
            CcrDate = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date()
            CcrMonth = CcrDate.month
            CcrYear = CcrDate.year

        syptSwpjxx = formatData('syptSwpjxx')
        if syptSwpjxx == [{}]:
            return u'缺失值'
        else:
            syptSwpjxx = pd.DataFrame(syptSwpjxx).dropna(how='all')
            if 'SWXYPJSJ' in list(syptSwpjxx.columns) and 'SWXYPJ' in list(syptSwpjxx.columns):
                if str(CcrYear) in list(syptSwpjxx['SWXYPJSJ']):
                    SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear)]['SWXYPJ'].iloc[-1], 'str')
                elif str(CcrYear-1) in list(syptSwpjxx['SWXYPJSJ']) and CcrMonth > 5:
                    SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear-1)]['SWXYPJ'].iloc[-1], 'str')
                elif str(CcrYear-1) in list(syptSwpjxx['SWXYPJSJ']) and CcrMonth <= 5:
                    SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear - 1)]['SWXYPJ'].iloc[-1], 'str')
                elif str(CcrYear-2) in list(syptSwpjxx['SWXYPJSJ']) and CcrMonth <= 5:
                    SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear - 2)]['SWXYPJ'].iloc[-1], 'str')
                else:
                    SWXYPJSJLastOne = None
                # 纳税等级校验
                if SWXYPJSJLastOne not in null_type_list:
                    return SWXYPJSJLastOne
                else:
                    return '缺失值'
            return '缺失值'
    except:
        return '缺失值'




if __name__ == '__main__':
    import json
    with open(r'C:\Users\john\Desktop\samples\case(21).json',encoding='utf8') as ff:
        TX_SX_DSJ = json.loads(ff.read())['TX_SX_DSJ']
    cQexecuteTime = ""
    result = countdownTwoYearsTaxAmtCheck()
    print(result)
result = countdownTwoYearsTaxAmtCheck()